<template>
  <el-card class="audit-form">
    <h2>商户资质审核</h2>

    <el-form label-width="80px">
      <el-form-item label="用户 ID">
        <el-input v-model.number="userId" readonly />
      </el-form-item>

      <el-form-item label="店铺名称">
        <el-input v-model="shopName" readonly />
      </el-form-item>

      <el-form-item label="营业执照">
        <el-link :href="businessLicense" target="_blank">{{ businessLicense }}</el-link>
      </el-form-item>

      <el-form-item label="审核状态">
        <el-select v-model.number="auditStatus" placeholder="请选择">
          <el-option label="通过" :value="1" />
          <el-option label="拒绝" :value="2" />
        </el-select>
      </el-form-item>

      <el-form-item label="驳回原因" v-if="auditStatus === 2">
        <el-input v-model="rejectReason" placeholder="请输入原因" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onAudit">提交审核</el-button>
      </el-form-item>
    </el-form>

    <!-- <el-alert
      v-if="result"
      title="返回结果"
      type="success"
      :description="JSON.stringify(result, null, 2)"
      show-icon
    />

    <el-alert
      v-if="error"
      title="出错信息"
      type="error"
      :description="JSON.stringify(error, null, 2)"
      show-icon
    /> -->
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { auditMerchant, getMerchantById } from '@/api/merchant'
import { useRoute } from 'vue-router'

const userId = ref(null)
const auditStatus = ref(null)
const rejectReason = ref('')
const shopName = ref('')
const businessLicense = ref('')
const result = ref(null)
const error = ref(null)
const route = useRoute()

onMounted(async () => {
  const uid = route.query.userId
  if (uid) {
    try {
      const res = await getMerchantById(uid)
      console.log("信息"+res.data)
      const merchant = res.data.data
      
      userId.value = merchant.userId
      auditStatus.value = merchant.auditStatus || null
      rejectReason.value = merchant.rejectReason || ''
      shopName.value = merchant.shopName || ''
      businessLicense.value = merchant.businessLicense || ''
    } catch (err) {
      console.error('加载商户信息失败:', err)
    }
  }
})

async function onAudit() {
  result.value = null
  error.value = null

  if (!userId.value) {
    ElMessage.warning('请填写 userId')
    return
  }
  if (auditStatus.value === null) {
    ElMessage.warning('请选择审核状态')
    return
  }

  const payload = {
    userId: userId.value,
    auditStatus: auditStatus.value,
    ...(auditStatus.value === 2 && { rejectReason: rejectReason.value })
  }

  try {
    const res = await auditMerchant(payload)
    result.value = res.data
    ElMessage.success('审核请求已发送')
  } catch (err) {
    console.error(err)
    error.value = err.response?.data || err.message
    ElMessage.error('审核失败')
  }
}
</script>

<style scoped>
.audit-form {
  max-width: 500px;
  margin: 2rem auto;
}
</style>
